import {isRef, Ref, ref, watchEffect} from "vue";
import {onReachBottom} from "@dcloudio/uni-app";

export function usePagination(params: {
    page: number
    pageSize: number
    onPageChange?: Function
    args?: any,
    startReachBottom?: boolean | Ref<boolean>
    onPageAfter?: Function,
    argsAfter?: any,
}){
    const page = ref(params.page)
    const argsAfter = ref(params.argsAfter)
    const pageSize = ref(params.pageSize)
    const loadStatus = ref<'loading' | 'over' | 'erro' | 'loadmore'>('loadmore')

    onReachBottom(() => {
        if (params.startReachBottom){
            if (isRef(params.startReachBottom) && !params.startReachBottom.value){
                return
            }
        }

        if (params.startReachBottom === false){
            return
        }

        if (loadStatus.value === 'over' || loadStatus.value === 'erro'){
            return
        }
        loadStatus.value = 'loading'
        page.value++
    })

    watchEffect(async () => {
        if (page.value < 0){
            return
        }

        if (params.onPageChange){
            try {
                await params.onPageChange(page.value, pageSize.value, isRef(params.args) ? params.args.value : params.args)
                if(params.onPageAfter){
                    params.onPageAfter(argsAfter)
                }
            }catch (err){
                switch (err){
                    case 'err':{
                        loadStatus.value = 'erro'
                        break
                    }

                    case 'nomore': {
                        loadStatus.value = 'over'
                        break
                    }
                }
            }
        }
    })

    return {
        page,
        loadStatus,
        argsAfter,
    }
}
